<?php
class Booking extends CI_Controller{
	public function __construct()
	{
		parent::__construct();
		$this->load->helper('url');
		$this->load->helper('myfun');
		$this->load->helper('json');
		$this->load->model('cust_info_model');
		$this->load->model('work_day_model');
		$this->load->model('book_info_model');
		$this->load->library('session');
		$this->load->library('email');
	}

	function login(){
		$data['errMsg'] = "";
		$this->load->view('booking/login',$data);
	}
	function logout(){
		$this->session->sess_destroy();
		redirect('booking/login','refresh');
	}
	function index(){
		if( ! $this->session->userdata('login_c'))
		{
			redirect('booking/login','refresh');
		}
		$data['email'] = $this->session->userdata('email');
		$this->load->view('booking/index',$data);
	}
	function reg(){
		$data['query']=$this->cust_info_model->getAllCustInfo();
		$this->load->view('booking/reg',$data);
	}

	function doReg(){
		$id = $this->cust_info_model->addCustInfo();

		//sendmail to cust
		$email=$_POST['email'];
		$pw=$_POST['password'];
		$emailMsg = "Welcome to ".base_url()." ! Thank you for signup as our client.\n\n".
			"Please confirm your information below.\n\n".
			"Your member login information:\n".                                      
			"UserID: ".$email."\n".                                     
			"Password: ".$pw."\n\n".   
			"Your email address: ".$email."\n\n".     
			"Let's get started and make your appointment for your favorite designer.\n".                                                           
			"User your userID and password login our frontpage and get your appointment done in the following page.\n\n".
			"Sincerely,\n".
		base_url();

		$this->email->from($this->email->getFromMail(), 'system');
		$this->email->to($email);
		$this->email->subject('confirm your account');
		$this->email->message($emailMsg);
		$this->email->send();
		//

		$data['errMsg'] = "<SCRIPT type=text/javascript>alert('Successfully registered, please login!');</SCRIPT>";
		$this->load->view('booking/login',$data);

	}

	function doLogin(){
		$flag = $this->cust_info_model->checkLogin();
		$data['errMsg'] = "";
		if(!$flag || $_POST['email']=='' || $_POST['password']==''){
			$data['errMsg'] = "You are not logged In";
			$this->load->view('booking/login',$data);
		}else{
			$sess_data = array(
					'login_c' => True,
					'email'=>$_POST['email']
			);
			$this->session->set_userdata($sess_data);
			redirect('booking/index','refresh');
		}
	}

	function doBook(){
		$data['email'] = $this->session->userdata('email');

		$id = $this->book_info_model->addBookInfo();
		//sendEmail
		$query = $this->book_info_model->getEmailMsg($id);
		$row = $query->row_array();

		$email = $row['email'];
		$bookday = $row['bookday'];
		$booktime = $row['booktime'];
		$serverna = $row['serverna'];
		$custna = $row['custna'];
		$employena = $row['employena'];

		$emailMsg = "Client ".$custna." has scheduled your service at ".$booktime." on "
		.$bookday.". The required style is ".$serverna
		.". Please be on time. Thank you for your hard work. Good day!";

		$this->email->from($this->email->getFromMail(), 'system');
		$this->email->to($email);
		$this->email->subject('You have an appointment');
		$this->email->message($emailMsg);
		$this->email->send();
		//echo $this->email->print_debugger();

		//sendEmail to cust
		$emailMsg = "Welcome to ".base_url()." ! Thank you for your appointment.\n\n".
			"Please confirm your information below.\n\n".			
			"Your appointment is scheduled at ".$booktime." on ".$bookday." with designer ".$employena.".\n\n".
		$employena." is a very talented designer and your chosen style is ".$serverna.".Please enjoy!\n\n".
			"Again, please confirm your appointment:\n\n".			
			"Designer: ".$serverna."\n".
			"Date: ".$bookday."\n".
			"Time: ".$booktime."\n\n".			
			"We are looking forwards for your arrival wholehearted!\n".
			"Sincerely,\n".
		base_url();


		$this->email->clear();
		$this->email->from($this->email->getFromMail(), 'system');
		$this->email->to($data['email']);
		$this->email->subject('Your appointment has been scheduled');
		$this->email->message($emailMsg);
		$this->email->send();

		$data['resultMsg'] = "<SCRIPT type=text/javascript>alert('System has send mail to the Designer email.');</SCRIPT>";
			
		//redirect('booking/index','refresh');
		$this->load->view('booking/index',$data);
	}

	function getServers(){
		$my_data = $this->cust_info_model->getServer();
		if($my_data->num_rows() > 0){
			foreach($my_data->result() as $row)
			{
				$item = Array("serverid" => $row->serverid,
		                      "serverna" => $row->serverna); 
				$itemList[] = $item;
			}
			$rows = $my_data->num_rows();
			$data = json_encode($itemList);
			print '{"total":"' . $rows . '","results":' . $data . '}';
		}
		else
		print '{"total":"0","results":""}';
	}

	function getEmploye(){
		$serverid = $this->uri->segment(3);
		$my_data = $this->cust_info_model->getEmploye($serverid);
		if($my_data->num_rows() > 0){
			foreach($my_data->result() as $row)
			{
				$item = Array("employeid" => $row->employeid,
	                      "employena" => $row->employena); 
				$itemList[] = $item;
			}
			$rows = $my_data->num_rows();
			$data = json_encode($itemList);
			print '{"total":"' . $rows . '","results":' . $data . '}';
		}
		else
		print '{"total":"0","results":""}';
	}

	function getInfo(){
		$email = $this->uri->segment(3);
		$my_data = $this->cust_info_model->getInfo($email);
		if($my_data->num_rows() > 0){
			foreach($my_data->result() as $row)
			{
				$item = Array("custna" => $row->custna,
						  "custid" => $row->custid,
	                      "phone" => $row->phone); 
				$itemList[] = $item;
			}
			$rows = $my_data->num_rows();
			$data = json_encode($itemList);
			print '{"total":"' . $rows . '","results":' . $data . '}';
		}
		else
		print '{"total":"0","results":""}';
	}

	function checkPostBook(){
		$msg = "";
		$id = $this->uri->segment(3);
		$id = str_replace("a",":",$id);
		$arrid=split("_", $id );
		$bookday = str_replace("-","/",$arrid[0]);
		$employeid = $arrid[1];
		$booktime = $arrid[2];
		$serverid = $arrid[3];

		//check day
		if($this->book_info_model->checkIsHoliday($bookday))
		$msg = " This is holiday time!";
		//workingday
		else if(!$this->book_info_model->checkIsEmployeWorkDay($bookday,$arrid[1]))
		$msg = "The Designer is out of work today!";
		else {
			$msg = $this->checkBookTime($bookday."_".$employeid."_".$booktime."_".$serverid);
		}
			
		print '{"msg":"'.$msg.'"}';
	}

	function searchBookInfo(){
		/*$data=array(
			'employena'=>$_POST['employena'],
			'bookday'=>$_POST['bookday']
			);
			$temp1 = array_shift($data); //第一个参数
			$temp2 = array_shift($data); //第二个参数
			*/
		$data['query']=$this->book_info_model->getFilterBookInfo();
		$data['employeinfo']=$this->db->query('select employeid,employena from employe_info');
		$this->load->view('admin/workDay/search_bookinfo',$data);
	}

	function getBookInfo(){
		//	$data['query']=$this->book_info_model->getAllBookInfo();
		$data['query']=$this->db->query('select a.id,a.employeid,a.bookday,a.booktime,a.status,b.custna,c.serverna,d.employena from book_info a left join cust_info b on a.custid=b.custid left join  server_info c on a.serverid = c.serverid left join employe_info d on a.employeid = d.employeid');
		$data['employeinfo']=$this->db->query('select employeid,employena from employe_info');
		$this->load->view('admin/workDay/search_bookinfo',$data);
	}

	function getWorkingDay($id){
		$weekarray=array("SUN","MON","TUR","WED","THU","FRI","SAT");
		$msg = ",0,1,2,3,4,5,6";

		$query = $this->work_day_model->getWorkDayByEmployeId($id);
		if($query->num_rows() > 0){
			foreach($query->result() as $row)
			{
				//$msg=$msg.",".$weekarray[$row->workday];
				$msg=str_replace(",".$row->workday,"",$msg);
			}
			if(strlen($msg)>0)
			$msg=substr($msg,1);
		}
		return $msg;//"Designer's working days are ".$msg;
	}

	function getWorkingDayAjax(){
		$id = $this->uri->segment(3);
		print '{"msg":"'.$this->getWorkingDay($id).'"}';
	}

	function checkBookDay($id){
		$msg = "";
		$msg1 = "";
		$arrid=split("_", $id );
		$bookday = str_replace("-","/",$arrid[0]);

		//holiday
		if($this->book_info_model->checkIsHoliday($bookday))
		$msg = "This is holiday time!";

		//workingday
		else if(!$this->book_info_model->checkIsEmployeWorkDay($bookday,$arrid[1]))
		$msg = "The Designer is out of work today!";

		//worktime
		else {
			$str = $this->book_info_model->getWorkTimeAndBookedTime($bookday,$arrid[1]);
			$arrmsg = split("_", $str );
			$msg="Designer's working hours are ".$arrmsg[0];
			$msg1=$arrmsg[1];
		}
		return $msg."_".$msg1;

	}

	function checkBookDayAjax(){
		$id = $this->uri->segment(3);
		$arrstr = $this->checkBookDay($id);
		$arr = split("_", $arrstr);
		$arrmsg1 = $arr[1];
		if($arrmsg1!="")
		$arrmsg1 = "These durations of this designer have been arranged	(".$arrmsg1.")";
		print '{"msg":"'.$arr[0].'","msg1":"'.$arrmsg1.'"}';
	}

	function checkBookTime($id){
		$msg = "";
		$msg1 = "";
		$id = str_replace("a",":",$id);
		$arrid=split("_", $id );
		$bookday = str_replace("-","/",$arrid[0]);
		$employeid = $arrid[1];
		$booktime = $arrid[2];
		$serverid = $arrid[3];

		//is worktime
		if(!$this->book_info_model->isWorkTime($bookday,$employeid,$booktime))
		$msg = "Out of designer's working period!";

		//workingday
		else if(!$this->book_info_model->checkIsEmployeFreeTime($bookday,$booktime,$employeid,$serverid))
		$msg = "Someone has booked this working time of the designer!";
			
		return $msg;
	}
	function checkBookTimeAjax(){
		$id = $this->uri->segment(3);
		print '{"msg":"'.$this->checkBookTime($id).'"}';
	}

}
?>